<template>
  <div>
    <div class="text-right" v-if="hasContract">
      <el-button class="mb-2" @click="handleView">查看合同</el-button>
      <el-button
        :loading="refuseLoading"
        class="float-right mr-2"
        @click="getRefush()"
        icon="el-icon-refresh"
      >
        刷新
      </el-button>
    </div>
    <el-form :model="related" label-position="left" size="small" label-width="150px">
      <el-form-item label="是否有共同借款人">
        <span v-if="isView">{{ { 0: '否', 1: '是' }[related.is_comm_loan] }}</span>
        <template v-else>
          <el-radio v-model="related.is_comm_loan" label="1">是</el-radio>
          <el-radio v-model="related.is_comm_loan" label="0">否</el-radio>
        </template>
      </el-form-item>
      <template v-if="+related.is_comm_loan === 1">
        <el-form-item label="共同借款人">
          <el-button size="mini" @click="addPerson" v-if="!isView">
            <i class="fa fa-plus"></i>
            新增共同借款人
          </el-button>
          <table
            style="line-height: 1.2rem"
            class="table table-bordered table-sm bg-white table-vertical-middle text-center"
          >
            <colgroup>
              <col width="12%" />
              <col width="15%" />
              <col width="12%" />
              <col width="16%" />
              <col width="20%" />
              <col width="15%" />
              <col width="10%" />
            </colgroup>
            <tr>
              <td>类型</td>
              <td>主体名称</td>
              <td>法人名字</td>
              <td>联系电话</td>
              <td>证件号</td>
              <td>地址</td>
              <td v-if="!isView">操作</td>
            </tr>
            <tr v-for="(p, index) of personData" :key="index">
              <td>{{ enumEntityType[p.com_person_type] }}</td>
              <td>{{ p.person_name }}</td>
              <td>{{ +p.com_person_type === 1 ? p.person_name_corp : '-' }}</td>
              <td>{{ p.person_phone }}</td>
              <td>{{ p.cert_no }}</td>
              <td>{{ p.person_address }}</td>
              <td v-if="!isView">
                <el-button type="text" @click="addPerson(p, index)">
                  <i class="fa fa-edit"></i>
                </el-button>
                <el-button type="text" @click="deletePerson(index)">
                  <i class="fa fa-trash text-danger"></i>
                </el-button>
              </td>
            </tr>
            <tr v-if="!personData.length">
              <td :colspan="isView ? 6 : 7" class="text-muted">请先新增共同借款人</td>
            </tr>
          </table>
        </el-form-item>
      </template>
    </el-form>
    <table class="table table-bordered table-vertical-middle" v-loading="loading">
      <tr>
        <td class="text-center font-weight-bold" width="4%" :rowspan="14">委托担保合同</td>
        <td class="td-label" width="12%">贷款主体</td>
        <td width="36%">{{ relatedData.customer_name || '-' }}</td>
        <td class="td-label" width="12%">客户类型</td>
        <td width="36%">{{ orgClassName || '-' }}</td>
      </tr>
      <tr>
        <td class="td-label">联系人</td>
        <td>{{ relatedData.corp_name }}</td>
        <td class="td-label">联系电话</td>
        <td>{{ relatedData.mobile_no }}</td>
      </tr>
      <tr>
        <td class="td-label">
          <span class="text-danger">*</span>
          地址
        </td>
        <td :class="tdClass">
          <span v-if="isView">{{ contract.entrust_entity_address || '-' }}</span>
          <input
            v-else
            class="form-control"
            placeholder="请填写客户地址"
            v-model="contract.entrust_entity_address"
          />
        </td>
        <!-- registerData.bank_name || relatedData.bank_name -->
        <td class="td-label">
          <span class="text-danger">*</span>
          放款银行名称
        </td>
        <td :class="tdClass">
          <span v-if="isView">{{ contract.bank_name || '-' }}</span>
          <input
            v-else
            class="form-control"
            placeholder="请填写放款银行名称"
            v-model="contract.bank_name"
          />
        </td>
      </tr>
      <tr>
        <td class="td-label">保证合同签订银行名称</td>
        <td :class="tdClass">
          <span v-if="isView">{{ contract.entrust_bank_name || '-' }}</span>
          <input
            v-else
            class="form-control"
            placeholder="请填写保证合同签订银行名称"
            v-model="contract.entrust_bank_name"
          />
        </td>
        <td class="td-label">
          <span class="text-danger">*</span>
          贷款利率
        </td>
        <td :class="tdClass">
          <span v-if="isView">{{ contract.load_rate || '-' }}%</span>
          <div class="d-flex align-items-center" v-else>
            <input
              v-input-number="{ min: 0, max: 100, fixed: 2 }"
              class="form-control"
              placeholder="请填写"
              v-model="contract.load_rate"
            />
            <span class="px-3 text-muted">%</span>
          </div>
        </td>
      </tr>
      <tr>
        <td class="td-label">借款合同</td>
        <td :class="tdClass">
          <span v-if="isView">{{ contract.loan_contract_no || '-' }}</span>
          <div class="d-flex align-items-center" v-else>
            <input
              class="form-control"
              placeholder="合同编号"
              v-model="contract.loan_contract_no"
            />
            <el-date-picker
              v-model="contract.contract_date"
              type="date"
              placeholder="合同签订时间"
              class="w-100 start-date-pick"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </div>
        </td>
        <td class="td-label">
          <span class="text-danger">*</span>
          授信/借款金额
        </td>
        <td :class="tdClass">
          <span v-if="isView">{{ contract.reply_funds || '-' }}万元</span>
          <div class="d-flex align-items-center" v-else>
            <el-input
              clearable
              v-input-number="{ min: 0, fixed: 2 }"
              class="form-control"
              @change="setGuaFee"
              placeholder="请填写"
              v-model="contract.reply_funds"
            ></el-input>
            <div class="px-3 text-muted" style="min-width: 60px">万元</div>
          </div>
        </td>
      </tr>
      <tr>
        <td class="td-label">保证合同号</td>
        <td :class="tdClass">
          <span v-if="isView">{{ contract.ensure_contract_no || '-' }}</span>
          <div class="d-flex align-items-center" v-else>
            <input
              class="form-control"
              placeholder="请填写"
              v-model="contract.ensure_contract_no"
            />
          </div>
        </td>
        <td class="td-label">
          <span class="text-danger">*</span>
          贷款期限
        </td>
        <td :class="tdClass">
          <span v-if="isView">{{ contract.load_years || '-' }}月</span>
          <div class="d-flex align-items-center" v-else>
            <el-input
              class="form-control"
              placeholder="请填写"
              v-model="contract.load_years"
              @change="setGuaFee"
              v-input-number="{ min: 0, max: 120, fixed: 0 }"
            ></el-input>
            <span class="px-3 text-muted">月</span>
          </div>
        </td>
      </tr>
      <tr>
        <td class="td-label">
          <span class="text-danger">*</span>
          贷款品种
        </td>
        <td :class="tdClass">
          <span v-if="isView">{{ debitType[contract.loan_varieties] || '-' }}</span>
          <div v-else>
            <c-select
              :options="debitType"
              class="w-100"
              placeholder="选择贷款品种"
              v-model="contract.loan_varieties"
            ></c-select>
          </div>
        </td>
        <td class="td-label">
          <!-- <span class="text-danger">*</span> -->
          担保费率
        </td>
        <td :class="tdClass">
          <span v-if="isView">{{ contract.gua_rate || '-' }}%</span>
          <div class="d-flex align-items-center" v-else>
            <input
              v-input-number="{ min: 0, max: 100, fixed: 2 }"
              class="form-control"
              @change="setGuaFee"
              placeholder="请填写"
              v-model="contract.gua_rate"
            />
            <span class="px-3 text-muted">%</span>
          </div>
        </td>
      </tr>
      <tr>
        <td class="td-label">
          <!-- <span class="text-danger">*</span> -->
          保费收取方式
        </td>
        <td :class="tdClass" colspan="3">
          <span v-if="isView">
            {{ enumGuaFundsSelfType[contract.gua_fee_coll_type] }}
          </span>
          <div style="padding: 0.6rem; background-color: #ffffee" v-else>
            <c-radio-group
              v-model="contract.gua_fee_coll_type"
              :options="enumGuaFundsSelfType"
              @change="setGuaFee"
            ></c-radio-group>
          </div>
        </td>
        <!-- <td class="td-label">担保费</td>
        <td :class="tdClass">
          <span v-if="isView">
            每年担保费：{{ contract.gua_fee_per || '-' }}元 合计：{{ contract.gua_fee || '-' }}元
          </span>
          <div class="d-flex align-items-center" v-else>
            <el-input
              v-model="contract.gua_fee_per"
              v-input-number="{ min: 0, fixed: 2 }"
              placeholder="每年收取担保费"
            ></el-input>
            元
            <el-input
              v-model="contract.gua_fee"
              v-input-number="{ min: 0, fixed: 2 }"
              placeholder="请输入担保费合计"
            ></el-input>
            元
          </div>
        </td> -->
      </tr>
      <tr>
        <td class="td-label">
          <!-- <span class="text-danger">*</span> -->
          担保费
        </td>
        <td :class="tdClass" colspan="3" class="p-0">
          <table class="table table-borderless bg-white table-vertical-middle m-0">
            <colgroup>
              <col width="33%" />
              <col width="33%" />
              <col width="33%" />
            </colgroup>
            <tr>
              <td class="border-right">预计缴费时间</td>
              <td class="border-right">计划在保余额</td>
              <td>缴费金额</td>
            </tr>
            <template v-for="(item, index) of guaFeeData">
              <tr :key="index">
                <td :class="tdClass" class="border-top border-right">
                  <span v-if="isView">
                    {{ $utils.dateFormat(item.due_warrant_date, 'yyyy-MM-dd') }}
                  </span>
                  <el-date-picker
                    v-else
                    class="w-100"
                    v-model="item.due_warrant_date"
                    @change="setDueDate(item.due_warrant_date, index)"
                    placeholder="缴费时间"
                    type="date"
                    value-format="yyyy-MM-dd"
                  ></el-date-picker>
                </td>
                <td :class="tdClass" class="border-top border-right">
                  <span v-if="isView">{{ item.plan_left_funds }} 万元</span>
                  <el-input
                    v-else
                    v-input-number="{ min: 0, fixed: 2 }"
                    placeholder="计划在保余额"
                    :disabled="+contract.gua_fee_coll_type === 1"
                    v-model="item.plan_left_funds"
                    @change="setItemFee(item.plan_left_funds, item)"
                  >
                    <span slot="append">万元</span>
                  </el-input>
                </td>
                <td :class="tdClass" class="border-top">
                  <span v-if="isView">{{ item.actual_warrant_fee }} 万元</span>
                  <el-input
                    v-else
                    v-input-number="{ min: 0, fixed: 2 }"
                    placeholder="缴费金额"
                    :disabled="+contract.gua_fee_coll_type === 1"
                    v-model="item.actual_warrant_fee"
                  >
                    <span slot="append">万元</span>
                  </el-input>
                </td>
              </tr>
            </template>
          </table>
        </td>
      </tr>
      <tr>
        <td class="td-label">
          <span class="text-danger">*</span>
          还款方式
        </td>
        <td colspan="3" :class="tdClass">
          <div v-if="isView">{{ contract.repay_method || '' }}</div>
          <el-input
            v-else
            type="textarea"
            placeholder="还款方式"
            :rows="5"
            v-model="contract.repay_method"
          ></el-input>
        </td>
      </tr>
      <tr>
        <td class="td-label">反担保措施</td>
        <td colspan="3" :class="tdClass">
          <span v-if="isView">{{ contract.gua_method_des }}</span>
          <el-input
            v-else
            type="textarea"
            placeholder="反担保措施"
            :rows="5"
            v-model="contract.gua_method_des"
          ></el-input>
        </td>
      </tr>
      <tr>
        <td class="td-label">合同设置</td>
        <td colspan="3" :class="tdClass">
          <span v-if="isView">
            本合同一式{{ contract.num_copes || '-' }}份，双方各执{{ contract.num_copes_per || '-' }}
            份，办理相关法律手续所需文本按需设置。
          </span>
          <div v-else class="d-flex align-items-center px-2">
            本合同一式
            <el-input
              style="width: 5rem"
              v-model="contract.num_copes_lower"
              placeholder="共计"
              v-input-number="{ min: 0, fixed: 0 }"
            ></el-input>
            份，双方各执
            <el-input
              style="width: 5rem"
              v-model="contract.num_copes_per_lower"
              placeholder="各执"
              v-input-number="{ min: 0, fixed: 0 }"
            ></el-input>
            份，办理相关法律手续所需文本按需设置。
          </div>
        </td>
      </tr>
    </table>
    <div v-if="(reSign || isSYSTEM) && !isView">
      <c-select
        :options="{
          0: '不盖章(客户线下签约时选择)',
          1: '加盖公章',
        }"
        :number-key="true"
        v-model="signStatus"
      ></c-select>
    </div>
    <div class="text-center py-4" v-if="!isView">
      <el-button type="primary" class="btn-long" :loading="submitLoading" @click="submit">
        {{ hasContract ? '修改' : '提交' }}委托合同
      </el-button>
      <!-- <el-button class="btn-long"
                  :loading="submitLoading"></el-button> -->
    </div>

    <el-dialog
      top="30px"
      width="900px"
      append-to-body
      :close-on-click-modal="false"
      :before-close="beforeClose"
      :visible.sync="entrustView"
    >
      <pdf-view :contract-id="contractId" :query-id="queryId" :view-mode="true"></pdf-view>
    </el-dialog>

    <common-person
      :visible.sync="editCommonVisible"
      :form-data="editCommonForm"
      @back="setPerson"
      :attach="[]"
    ></common-person>
  </div>
</template>

<script>
import { enumCompanyType } from '@/gov/plugins/enum'
import { mapGetters } from 'vuex'
import { nzhToMoney, mul, nzhToNum, add } from '@vimi/utils-tool'
import { enumGuaFundsSelfType } from '@/credit/views/county/unionProvince/components/projectApprove/index'
import PdfView from '@/credit/views/county/unionProvince/components/PdfView'
import CommonPerson from '@/credit/views/city/program/ocr/CommonPerson'
import { enumEntityType } from '@/credit/views/county/unionProvince/components/ContractGuardMortgage'
import { checkMobile } from '@/common/plugins/validator'
export default {
  props: {
    viewMode: {
      type: Boolean,
      default: false,
    },
    relatedData: {
      type: Object,
      default: () => ({}),
    },
    reSign: {
      type: Boolean,
      default: false,
    },
  },
  components: {
    PdfView,
    CommonPerson,
  },
  data() {
    return {
      enumEntityType,
      enumGuaFundsSelfType,
      enumCompanyType,
      loading: false,
      debitType: {
        1: '流贷',
        2: '固贷',
        3: '其他',
      },
      related: {
        is_comm_loan: '0',
      },
      personData: [],
      submitLoading: false,
      contract: {
        gua_org_id: '',
        accept_entrust_entity_name: '',
      },
      registerData: {}, // 审批秘书登记结果
      entrustView: false,
      guaFeeData: [],
      editCommonVisible: false,
      editCommonForm: {},
      editIndex: '-1',
      personTable: 'comm_loan_person',
      mainPerson: {},
      refuseLoading: false,
      signStatus: 1,
    }
  },
  computed: {
    ...mapGetters(['entrustContract', 'org', 'clientId', 'enumOrgClassObj']),
    contractId() {
      return this.entrustContract.doc_id
    },
    isView() {
      // return false
      return this.viewMode || +this.entrustContract.sign_status > 0
    },
    tdClass() {
      return this.isView ? '' : 'input-td'
    },
    hasContract() {
      return !!this.entrustContract.entrust_contract_id
    },
    contractEditId() {
      return this.entrustContract.entrust_contract_id
    },
    queryId() {
      return this.relatedData.customer_related_id
    },
    isSYSTEM() {
      // 系统后台查所有
      return this.org.orgClass === 'org_credit_sys'
    },
    orgName() {
      return this.org.orgName
    },
    orgClassName() {
      return this.enumOrgClassObj[this.relatedData.org_class] || ''
    },
  },
  watch: {
    queryId: {
      handler: function () {
        if (!this.queryId) {
          return
        }
        this.related.is_comm_loan = this.relatedData.is_comm_loan || '0'
        this.loading = true
        // 获取调查审批秘书登记内容及上一次委托合同的联合担保协议编号及时间,组织信息内
        Promise.all([
          this.getRegisterData(),
          this.getPerson(),
          this.$store.dispatch('getEntrustContract', this.queryId),
        ]).finally(() => {
          this.initContractByExist()
          this.loading = false
        })
      },
      immediate: true,
    },
  },
  created() {
    this.$store.dispatch('getEnumOrgClass')
  },
  methods: {
    getRefush() {
      this.refuseLoading = true
      this.$store.dispatch('getEntrustContract')
      this.$store.dispatch('getEntrustContract', this.queryId).finally(() => {
        this.refuseLoading = false
      })
    },
    getPerson() {
      return this.$api
        .getData(
          this.$serviceName,
          this.personTable,
          { 'customer_related_id.eq': this.queryId },
          { is_main: 'desc' }
        )
        .then(res => {
          const data = res?.data ?? []
          this.personData = data.filter(item => +item.is_main === 0)
          this.mainPerson = data.find(item => +item.is_main === 1) || {}
        })
    },
    setPerson(person) {
      if (this.editIndex === -1) {
        this.personData.push(person)
      } else {
        this.personData[this.editIndex] = { ...person }
      }
    },
    addPerson(row = {}, index = -1) {
      this.editCommonVisible = true
      this.editCommonForm = { ...row }
      this.editIndex = index
    },
    deletePerson(index) {
      if (this.personData.length < 2) {
        return this.$message.warning('最少需添加一个共同借款人')
      }
      this.personData.splice(index, 1)
    },
    setDueDate(v, i) {
      const startDate = new Date(v)
      this.guaFeeData = this.guaFeeData.map((item, index) => {
        if (index > i) {
          item.due_warrant_date = v
            ? `${startDate.getFullYear() + index - i}-${
                startDate.getMonth() + 1
              }-${startDate.getDate()}`
            : ''
        }
        return item
      })
    },
    setItemFee(v, item) {
      item.actual_warrant_fee = Math.round(mul(v, 100, this.contract.gua_rate)) / 10000
    },
    setGuaFee() {
      if (!+(this.contract.gua_rate || '')) {
        this.guaFeeData = []
        return
      }
      const years = Math.ceil(+(this.contract.load_years || '') / 12)
      if (+this.contract.gua_fee_coll_type !== 2) {
        this.guaFeeData = []
        this.guaFeeData.push({
          actual_warrant_fee:
            Math.round(
              mul(+(this.contract.reply_funds || ''), 100, +(this.contract.gua_rate || ''), years)
            ) / 10000,
          due_warrant_date: '',
          plan_left_funds: this.contract.reply_funds,
          customer_related_id: this.queryId,
          gua_rate: this.contract.gua_rate,
        })
        return
      }

      this.guaFeeData = []
      for (let i = 1; i <= years; i++) {
        this.guaFeeData.push({
          actual_warrant_fee:
            Math.round(
              mul(+(this.contract.reply_funds || ''), 100, +(this.contract.gua_rate || ''))
            ) / 10000,
          due_warrant_date: '',
          plan_left_funds: this.contract.reply_funds,
          customer_related_id: this.queryId,
          gua_rate: this.contract.gua_rate,
        })
      }
    },
    beforeClose() {
      this.entrustView = false
    },
    handleView() {
      this.entrustView = true
    },
    getGuaFeeData() {
      return this.$api
        .getData({
          table: 'credit_warrant_fee_record',
          params: {
            'customer_related_id.eq': this.queryId,
          },
        })
        .then(res => {
          this.guaFeeData = res?.data ?? []
          if (!this.guaFeeData.length && !this.isView) {
            this.setGuaFee()
          }
        })
    },
    getRegisterData() {
      return this.$api
        .getData(
          this.$serviceName,
          'project_approval_register',
          {
            'customer_related_id.eq': this.queryId,
            'approval_register_type.in': '1,2',
          },
          {
            approval_register_type: 'desc',
          }
        )
        .then(res => {
          this.registerData = res?.data?.[0] ?? {}
        })
    },
    submit() {
      if (!this.queryId) {
        return
      }
      for (let i = 0; i < this.guaFeeData.length; i++) {
        if (
          !this.guaFeeData[i].due_warrant_date ||
          !this.guaFeeData[i].plan_left_funds ||
          !this.guaFeeData[i].actual_warrant_fee
        ) {
          return this.$message.warning('请完善担保费信息')
        }
        this.guaFeeData[i].due_warrant_fee =
          +this.contract.gua_fee_coll_type === 1
            ? Math.round(
                mul(+(this.contract.reply_funds || ''), 100, +(this.contract.gua_rate || ''))
              ) / 10000
            : this.guaFeeData[i].actual_warrant_fee
        this.guaFeeData[i].gua_rate = this.contract.gua_rate
      }
      this.contract.gua_fee = this.guaFeeData.reduce(
        (prev, curr) => add(prev, curr.actual_warrant_fee),
        0
      )
      if (!this.validator()) return

      this.contract.reply_funds_yuan = +this.contract.reply_funds * 10000
      this.contract.gua_org_id = this.relatedData.service_id
      this.contract.reply_funds_capital = nzhToMoney(this.contract.reply_funds_yuan)
      this.contract.gua_fee_total_capital = nzhToMoney(+this.contract.gua_fee * 10000)
      // const yearCapital = this.contract.gua_fee /
      this.contract.gua_fee_capital = nzhToMoney(+this.contract.gua_fee_per)
      const date = this.contract.create_time || new Date()
      this.contract.sign_date = this.$utils.dateFormat(date, 'yyyy年MM月dd日')
      this.contract.num_copes_per = this.contract.num_copes_per_lower
        ? nzhToNum(this.contract.num_copes_per_lower)
        : ''
      this.contract.num_copes = this.contract.num_copes_lower
        ? nzhToNum(this.contract.num_copes_lower)
        : ''

      if (+this.related.is_comm_loan === 1 && this.personData.length < 1) {
        return this.$message.error('至少输入一个共同借款主体')
      }
      if (!checkMobile(this.contract.entrust_entity_phone)) {
        return this.$message.warning('贷款主体手机号错误')
      }
      const personData = this.personData.map(item => {
        item.customer_related_id = this.queryId
        return item
      })

      const mainPerson = {
        ...this.mainPerson,
        person_address: this.contract.entrust_entity_address,
        person_phone: this.contract.entrust_entity_phone,
      }
      personData.push(mainPerson)

      const updateformData = {
        masterTableInfo: JSON.stringify({
          customer_related_id: this.queryId,
          reply_funds: this.contract.reply_funds,
          months: this.contract.load_years,
          is_comm_loan: this.related.is_comm_loan,
          mobile_no: mainPerson.person_phone,
          gua_rate: this.contract.gua_rate,
          load_rate: this.contract.load_rate,
          gua_fee_coll_type: this.contract.gua_fee_coll_type,
        }),
        masterTableName: 'customer_related',
        slaveTableInfo: JSON.stringify(personData),
        slaveTableName: this.personTable,
        slaveTableInfo1: JSON.stringify(this.guaFeeData),
        slaveTableName1: 'credit_warrant_fee_record',
      }
      this.submitLoading = true
      this.$api
        .relatedUpdate(this.$serviceName, updateformData)
        .then(() => {
          if (this.hasContract) {
            this.putData()
          } else {
            this.postData()
          }
          this.getPerson()
          this.getGuaFeeData()
        })
        .catch(err => {
          if (err) {
            const errStr = typeof err.data === 'string' ? err.data : '操作失败，请重试！'
            return this.$message.error(`${errStr}`)
          }
        })
        .finally(() => {
          this.submitLoading = false
        })
    },
    async putData() {
      this.submitLoading = true
      const keys = [
        'approval_fee',
        'bank_name',
        'customer_related_id',
        'ensure_contract_no',
        'entrust_entity_address',
        'entrust_entity_cert_no',
        'entrust_entity_name',
        'entrust_entity_phone',
        'funds_use_dir',
        'gua_fee',
        'gua_fee_per',
        'gua_fee_capital',
        'gua_fee_total_capital',
        'gua_fee_coll_type',
        'gua_method_des',
        'gua_org_code',
        'gua_org_id',
        'gua_org_name_short',
        'gua_rate',
        'load_rate',
        'load_years',
        'loan_contract_no',
        'loan_varieties',
        'repay_method',
        'reply_funds',
        'reply_funds_capital',
        'sign_date',
        'entrust_entity_corp',
        'contract_date',
        'reply_funds_yuan',
        'num_copes_per',
        'num_copes',
        'num_copes_per_lower',
        'num_copes_lower',
        'entrust_bank_name',
        'bank_name',
      ]
      const data = {}
      keys.forEach(key => {
        data[key] = this.contract[key]
      })
      if (this.reSign) {
        //系统后台重做重签合同
        data.re_sign_type = 1
        data.sign_status = this.signStatus
      }
      const [res] = await this.$utils.promise(
        this.$api.updateData(this.$serviceName, 'entrust_contract', this.contractEditId, data)
      )

      this.submitLoading = false
      if (res) {
        this.$message.success('修改委托合同成功')
        this.$store.dispatch('getEntrustContract', this.queryId)
        this.$emit('success', 0)
        // this.$emit('close', false)
      } else {
        this.$message.error('修改委托合同失败')
      }
    },
    async postData() {
      this.submitLoading = true
      if (this.reSign) {
        //系统后台重做重签合同
        this.contract.re_sign_type = 1
        this.contract.sign_status = this.signStatus
      }
      const [res] = await this.$utils.promise(
        this.$api.addData(this.$serviceName, 'entrust_contract', this.contract)
      )

      this.submitLoading = false
      if (res) {
        this.$message.success('提交委托合同成功')
        this.$store.dispatch('getEntrustContract', this.queryId)
        this.$emit('nextTag', true)
        this.$emit('success', 1)
      } else {
        this.$message.error('提交委托合同失败')
      }
    },
    validator() {
      const enumValid = {
        load_rate: '请填写贷款利率',
        // loan_contract_no: '请填写授信合同/借款编号',
        // contract_date: '请选择借款合同签订时间',
        reply_funds: '请填写授信/借款金额',
        // ensure_contract_no: '请填写保证合同号',
        load_years: '请填写期限',
        loan_varieties: '请选择贷款品种',
        repay_method: '请输入还款方式',
        // gua_rate: '请填写担保费率',
        // gua_fee: '请填写担保费（总额）',
        bank_name: '请输入放款银行',
        // entrust_bank_name: '请输入保证合同签订银行',
        // num_copes_per_lower: '请输入合同份数',
        // num_copes_lower: '请输入合同份数',
      }

      const keys = Object.keys(enumValid)
      for (const key of keys) {
        if (!this.contract[key]) {
          this.$message.error(enumValid[key])
          return false
        }
      }

      return true
    },
    async initContractByExist() {
      if (this.hasContract) {
        this.contract = { ...this.entrustContract }
      } else {
        this.initContractByRelated()
      }
      this.loading = true
      await this.getGuaFeeData()
      this.loading = false
    },
    initContractByRelated() {
      this.contract = {
        gua_org_id: '',
        entrust_entity_name: this.relatedData.customer_name,
        entrust_entity_address: this.relatedData.address,
        entrust_entity_cert_no: this.relatedData.register_no || this.relatedData.lender_idcard,
        entrust_entity_phone: this.relatedData.mobile_no,
        entrust_entity_corp: this.relatedData.corp_name,
        bank_name: this.registerData.bank_name || this.relatedData.bank_name,
        load_rate: this.registerData.load_rate,
        funds_use_dir: this.registerData.funds_use_dir,
        reply_funds: this.registerData.res_funds,
        load_years: this.registerData.res_months,
        customer_related_id: this.relatedData.customer_related_id,
        gua_rate: this.registerData.gua_rate,
        approval_fee: this.registerData.approval_fee,
        gua_fee_coll_type: this.registerData.gua_fee_coll_type || '1',
        gua_fee: this.registerData.gua_fee,
        gua_fee_per:
          Math.round(+this.registerData.res_funds * this.registerData.gua_rate * 10000) / 100,
        gua_method_des: this.registerData.gua_method_des,
      }
    },
    guaFee(data) {
      let {
        gua_fee_coll_type: type = '',
        gua_rate: rate = '',
        load_years: months = '',
        reply_funds: funds = '',
      } = data
      type = +type
      rate = +rate * 1e-2
      funds = +funds * 1e4
      const year = Math.ceil(months / 12)
      if (type === 0 || rate === 0 || year === 0 || funds === 0) {
        return ''
      }
      if (type === 1) {
        return mul(funds, rate, year)
      }
      if (type === 2) {
        return mul(funds, rate)
      }
      return ''
    },
  },
}
</script>
<style lang="scss" scoped>
.table-vertical-middle td {
  vertical-align: middle;
}
.td-label {
  background-color: #f8f9fa;
  text-align: center;
}
.input-td {
  background-color: #ffffee;
}
</style>
